package com.example.jta_atomikos.service.impl;

import com.example.jta_atomikos.mapper.db1.OrderMapper;
import com.example.jta_atomikos.mapper.db2.OrderDetailMapper;
import com.example.jta_atomikos.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author wise-wang
 * 2021.12.05
 * 实现类，用于模拟事务回滚
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Override
    @Transactional
    public String insertDbaAndDbB(boolean flag) {
        //随机生成生产环境订单id，类型为UUID
        String orderId = UUID.randomUUID().toString();
        //插入订单
        orderMapper.insert(orderId, "从入门到放弃");

        //模拟报错,事务会回滚
        if (flag) {
            //flag=true的时候,触发2异常,事务回滚,为false的话,两个数据库都能正确插入数据
            System.out.println(1 / 0);
        }

        //插入订单明细
        orderDetailMapper.insert(1, orderId);
        return "success";
    }
}
